package com.example.phpclient;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.phpclient.student.MainStudent;


import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.HashMap;

public class Login_activity extends AppCompatActivity {
    RequestQueue queue;
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        queue = Volley.newRequestQueue(getApplicationContext());

        Button login = (Button) findViewById(R.id.button1);
//        final Button register = (Button)findViewById(R.id.button2);
        final EditText userNo = (EditText)findViewById(R.id.userNo);
        final EditText password = (EditText)findViewById(R.id.password);
        pref = getSharedPreferences("data",MODE_PRIVATE);
        Spinner level_spin = (Spinner)findViewById(R.id.level_spin1);
        final String[] levelItems = getResources().getStringArray(R.array.level);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,levelItems);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        level_spin.setAdapter(adapter);

        //登录
        //从preference加载
        if (pref.getString("userNo","").isEmpty()){}//获取不到时返回s1
        else {
            userNo.setText(pref.getString("userNo",""));
            password.setText(pref.getString("password",""));
            String level_string = pref.getString("level","");
            if (level_string.equals("学生")){
                level_spin.setSelection(1);
            }else {
                level_spin.setSelection(2);
            }

        }
        final Log_user user = new Log_user();
        level_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                user.setLevel(levelItems[i]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userNo_s = userNo.getText().toString();
                String password_s = password.getText().toString();
                String level_s = user.getLevel();//由于是后来改成spinner的所以和其他格式不太一样
                jsonRequest("login",userNo_s,password_s,level_s);
            }
        });

    }
    public void StringRequest(){
        String url="http://192.168.1.25/php_get.php?name=lzz&sex=man&age=21";//local 10.0.2.2         10.0.2.2:8080/php_get.php?name=lzz&sex=man&age=21
        //https://www.baidu.com     http://192.168.0.107/php_get.php?name=lzz&sex=man&age=21
        //创建一个字符串请求 参数（请求方式，URL，响应的回调接口，错误的回调接口）
        Toast toast= Toast.makeText(Login_activity.this,"ruan2",Toast.LENGTH_SHORT);
        toast.show();
        StringRequest request=new StringRequest(Request.Method.GET,
                url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast toast= Toast.makeText(Login_activity.this,response,Toast.LENGTH_SHORT);
                toast.show();
                //Log.d("TAG", response);
                //System.out.println(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast toast2= Toast.makeText(Login_activity.this,"ruan3",Toast.LENGTH_SHORT);
                toast2.show();

            }
        });
        queue.add(request);
    }

    public void jsonRequest(final String aim , String param1, String param2, String param3){//aim用于选择模式注册还是登录
        String url= this.getString(R.string.recUrl);

        HashMap<String, String> params = new HashMap<>();
        params.put("forwhat",aim);
        params.put("userNo",param1);
        params.put("password",param2);
        params.put("level",param3);
        JSONObject jsonObject = new JSONObject(params);

        Log.d("Tag",jsonObject.toString());
        final JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log_user user = JSON.parseObject(jsonObject.toString(), Log_user.class);//第一个参数是String的json
                        Log.d("TAG登录人",user.getLoged());
                        if (user.getLoged().equals("yes")){//java判断字符串相等不能用“==”
                            editor = getSharedPreferences("data",MODE_PRIVATE).edit();
                            editor.putString("userNo",user.getUserNo());
                            editor.putString("password",user.getPassword());
                            editor.putString("level",user.getLevel());
                            editor.apply();
                            if (user.getLevel().equals("学生")){
                                Intent intent = new Intent(Login_activity.this, MainStudent.class);
                                startActivity(intent);
                            }else {
                                Intent intent = new Intent(Login_activity.this,drawer_activity.class);
                                startActivity(intent);
                            }
                        }
                        else {
                            showExitDialog01();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d("TAG","fuckError");
                    }
                });
        queue.add(jsObjRequest);
    }

    private void showExitDialog01(){
        new AlertDialog.Builder(this)
                .setTitle("提示！")
                .setMessage("信息错误")
                .setPositiveButton("确定", null)
                .show();
    }
}
